$(document).ready(function () {
    laydate.skin('molv');
    /* 设置时间插件的皮肤 */
    var start = {
        elem: '#startTime',    //选择ID为START的input
        format: 'YYYY-MM-DD',  //自动生成的时间格式
        max: laydate.now(),    //最大日期
        istoday: false,        //是否是当天
        start: laydate.now(0, "YYYY-MM-DD"),  //设置开始时间为当前时间
        choose: function (datas) {
            over.min = datas;   //开始日选好后，重置结束日的最小日期
        }
    };
    var over = {
        elem: '#endTime',
        format: 'YYYY-MM-DD',
        max: laydate.now(),
        istoday: false,
        start: laydate.now(0, "YYYY-MM-DD"),
        choose: function (datas) {
            start.max = datas;  //结束日选好后，重置开始日的最大日期
        }
    };
    laydate(start);
    laydate(over);

    /*统计条件下拉框点击选项阻止收起事件*/
    $(".dropdown-menu").on("click", "[data-stopPropagation]", function (e) {
        e.stopPropagation();
    })

    var btnElement = '#SearchForm .dis, #userUseBtn .dis';
    btnJurisdiction(btnElement);//查询当前用户的按钮权限

    turnType();
    /*加载select下拉框数据*/
    loadBaseInfo();
    /*获取当前用户有权限的基地数据*/
    var url = "../map/retentionStatistics";
    loadToolRetention(url);
    /*调用加载表格数据方法*/
});

/*获取当前用户有权限的基地数据*/
function loadBaseInfo() {
    $.ajax({  //获取当前用户的基地权限
        type: "post",
        async: false,
        url: "../map/getBaseByUser",
        success: function (data) {
            if (data == "" || data == null) {  //如果当前用户没有基地权限时
                $('#baseTurn').html("");
            } else {
                /*加载搜索框内归属地下拉框数据*/
                var txt = '<option value="" selected="true">全部</option>';
                for (var i = 0; i < data.length; i++) {
                    txt += '<option  value="' + data[i].id + '">' + data[i].name + '</option>';
                }
                $('#baseTurn').html(txt);
                $('#baseTurn').selectpicker('refresh');
            }
        }
    });
}

/*获取工具类型、状态下拉框数据*/
function turnType() {
    $('#turnType').selectpicker('refresh');     //刷新下拉框
    $("#baseTurn").selectpicker('refresh');     //刷新下拉框
    /* 页面加载获取产品下拉框数据 */
    var tool_type = 'tool_type';
    var tool_status = 'tool_status';
    selecAjax(tool_type);
    selecAjax(tool_status);
}

/*调用后台接口获取select下拉框数据*/
function selecAjax(item) {
    $.ajax({
        type: "POST",
        data: {
            parentcode: item,
            tool: '123'
        },
        async: true,
        url: '../sysCodeListController/getSysCodeList',
        success: function (res) {
            var res = res.data;
            var txt = '<option value="" selected="true">全部</option>';
            var txt1 = '<option value="" selected="true">全部</option>';
            for (var i = 0; i < res.length; i++) {
                if (res[i].parentcode == "tool_type") {
                    txt += '<option  value="' + res[i].id + '">' + res[i].name + '</option>';
                    $('#typeTurn').html(txt);
                    $('#typeTurn').selectpicker('refresh');
                } else if (res[i].parentcode == "tool_status") {
                    txt1 += '<option value="' + res[i].id + '">' + res[i].name + '</option>';
                    $('#statusTurn').html(txt1);
                    $('#statusTurn').selectpicker('refresh');
                }
            }
        }
    });
}

/*初始化表格数据*/
function loadToolRetention(url) {
    $('#toolRetentionTable').bootstrapTable('destroy');
    /*表格加载前先销毁原有数据*/
    /*搜索条件*/
    var data = {};
    var time = new Date();
    var timeDate = new Date(time).Format("hh:mm:ss");  //获取当前系统时间
    var time1 = ($("#startTime").val()==null||$("#startTime").val()=="")?"":$("#startTime").val()+" 00:00:00";
    if(time1==""){
        var newDate = "";
    }else{
        var timeParse = Date.parse(time1);
        var newDate = new Date(timeParse);
    }
    data.startTime = newDate;
    var time2 = ($("#endTime").val()==null||$("#endTime").val()=="")?"":$("#endTime").val()+" "+timeDate;
    if(time2==""){
        var newDates = "";
    }else{
        var timeParses = Date.parse(time2);
        var newDates = new Date(timeParses);
    }
    data.endTime = newDates;
    data.base = $("#baseTurn").val();
    data.type = $("#typeTurn").val();
    data.status = $("#statusTurn").val();
    data.toolName = $("#SearchForm input[name='toolName']").val();
    data.no = $("#SearchForm input[name='no']").val();
    /*构造统计条件*/
    var colls = new Array();  //存放统计条件中选中项的name值
    $("#toolRetention input:checked").each(function (i) {
        if ($(this).attr("name") != "num") {
            colls.push($(this).attr("name"));
        }
    });
    data.colls = colls;
    /*初始化表格*/
    $('#toolRetentionTable').bootstrapTable({
        method: 'POST',
        url: url, /* 调用后台接口加载数据 */
        queryParamsType: '',
        queryParams: function (params) {
            /*var pageSize = params.pageSize;
            var pageNum = params.pageNumber;
            data.pageNum = pageNum;
            data.pageSize = pageSize;*/
            return JSON.stringify(data);
        },
        contentType: "application/json; charset=UTF-8",
        dataType:"json",
        cache: false,     // 不缓存
        striped: true,    // 隔行加亮
        pagination: true, //是否显示分页
        toolbar: '#userUseBtn',//工具列
        pageSize: 10,
        pageNumber: 1,     //初始化加载第一页，默认第一页
        pageList: [5, 10, 20, 30, 50], //可供选择的每页的行数（*）
        sidePagination: "client",
        showRefresh: true,  //是否显示刷新按钮
        columns: [
            {
                field: 'number',
                title: '序号',
                width: 20,
                align: "center",
                valign: "middle",
                formatter: function (value, row, index) {
                    return index + 1;
                }
            },
            {field: "baseName", title: "归属地", align: "center", valign: "middle", sortable: "true"},
            {field: "typeName", title: "工具类型", align: "center", valign: "middle", sortable: "true"},
            {field: "toolName", title: "工具名称", align: "center", valign: "middle", sortable: "true"},
            {field: "no", title: "工具编号", align: "center", valign: "middle", sortable: "true"},
            {field: "areaName", title: "滞留区域", align: "center", valign: "middle", sortable: "true"},
            {field: "areaChangeTime", title: "滞留时间", align: "center", valign: "middle", sortable: "true"},
            {field: "num", title: "数量", align: "center", valign: "middle", sortable: "true"}
        ],
        formatLoadingMessage: function () {
            return "请稍等，正在加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
        responseHandler: function (res) {
            var total, rows;
            if (res != null && res.length != 0) {
                /*total = res.total;*/
                rows = res.rows;
                var time = new Date();
                var timeDate = new Date(time).Format("yyyy-MM-dd hh:mm:ss");  //获取当前系统时间
                for (var i = 0; i < rows.length; i++) {
                    if (rows[i].areaChangeTime != "" || rows[i].areaChangeTime != null) {
                        /*工具最后更新时间*/
                        var formatterTime = new Date(rows[i].areaChangeTime).Format("yyyy-MM-dd hh:mm:ss");
                    }
                    var newTime = GetDateDiff(formatterTime, timeDate, "day"); //相差的时间分钟数
                    if (Number(res.lowRetention) <= Number(newTime) && Number(newTime) <= Number(res.midRetention)) {
                        /*layer.msg("低级滞留数据");*/
                        rows[i].no = '<span style="color: yellow;font-weight: bold">' + rows[i].no + '</span>';
                        rows[i].toolName = '<span style="color: yellow;font-weight: bold">' + rows[i].toolName + '</span>';
                        rows[i].typeName = '<span style="color: yellow;font-weight: bold">' + rows[i].typeName + '</span>';
                        rows[i].baseName = '<span style="color: yellow;font-weight: bold">' + rows[i].baseName + '</span>';
                        rows[i].areaName = '<span style="color: yellow;font-weight: bold">' + rows[i].areaName + '</span>';
                        if (rows[i].areaChangeTime == "" || rows[i].areaChangeTime == null) {
                            var times = "";
                        } else {
                            var times = new Date(rows[i].areaChangeTime).Format("yyyy-MM-dd hh:mm:ss");
                        }
                        rows[i].areaChangeTime = '<span style="color: yellow;font-weight: bold">' + times + '</span>';
                        rows[i].num = '<span style="color: yellow;font-weight: bold">' + rows[i].num + '</span>';
                    } else if (Number(res.midRetention) <= Number(newTime) && Number(newTime) < Number(res.highRetention)) {
                        /*layer.msg("中级滞留数据");*/
                        rows[i].no = '<span style="color: orange;font-weight: bold">' + rows[i].no + '</span>';
                        rows[i].toolName = '<span style="color: orange;font-weight: bold">' + rows[i].toolName + '</span>';
                        rows[i].typeName = '<span style="color: orange;font-weight: bold">' + rows[i].typeName + '</span>';
                        rows[i].baseName = '<span style="color: orange;font-weight: bold">' + rows[i].baseName + '</span>';
                        rows[i].areaName = '<span style="color: orange;font-weight: bold">' + rows[i].areaName + '</span>';
                        if (rows[i].areaChangeTime == "" || rows[i].areaChangeTime == null) {
                            var times = "";
                        } else {
                            var times = new Date(rows[i].areaChangeTime).Format("yyyy-MM-dd hh:mm:ss");
                        }
                        rows[i].areaChangeTime = '<span style="color: orange;font-weight: bold">' + times + '</span>';
                        rows[i].num = '<span style="color: orange;font-weight: bold">' + rows[i].num + '</span>';
                    } else if (Number(newTime) >= Number(res.highRetention)) {
                        /*layer.msg("高级滞留数据");*/
                        rows[i].no = '<span style="color: red;font-weight: bold">' + rows[i].no + '</span>';
                        rows[i].toolName = '<span style="color: red;font-weight: bold">' + rows[i].toolName + '</span>';
                        rows[i].typeName = '<span style="color: red;font-weight: bold">' + rows[i].typeName + '</span>';
                        rows[i].baseName = '<span style="color: red;font-weight: bold">' + rows[i].baseName + '</span>';
                        rows[i].areaName = '<span style="color: red;font-weight: bold">' + rows[i].areaName + '</span>';
                        if (rows[i].areaChangeTime == "" || rows[i].areaChangeTime == null) {
                            var times = "";
                        } else {
                            var times = new Date(rows[i].areaChangeTime).Format("yyyy-MM-dd hh:mm:ss");
                        }
                        rows[i].areaChangeTime = '<span style="color: red;font-weight: bold">' + times + '</span>';
                        rows[i].num = '<span style="color: red;font-weight: bold">' + rows[i].num + '</span>';
                    }else{
                        if (rows[i].areaChangeTime == "" || rows[i].areaChangeTime == null) {
                            var times = "";
                        } else {
                            var times = new Date(rows[i].areaChangeTime).Format("yyyy-MM-dd hh:mm:ss");
                        }
                        rows[i].areaChangeTime = times ;
                    }
                }
            } else {
                /*total = 0;*/
                rows = new Array();
            }
            return {
                /*"total": total,*///total,//总页数
                data: rows  //数据
            };
        }
    });

    /*比较两个时间相差的小时数-hour，天数-day，分钟数-minute，秒数-second*/
    function GetDateDiff(startTime, endTime, diffType) {
        //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式
        startTime = startTime.replace(/\-/g, "/");
        endTime = endTime.replace(/\-/g, "/");
        //将计算间隔类性字符转换为小写
        diffType = diffType.toLowerCase();
        var sTime = new Date(startTime); //开始时间
        var eTime = new Date(endTime); //结束时间
        //作为除数的数字
        var timeType = 1;
        switch (diffType) {
            case"second":
                timeType = 1000;
                break;
            case"minute":
                timeType = 1000 * 60;
                break;
            case"hour":
                timeType = 1000 * 3600;
                break;
            case"day":
                timeType = 1000 * 3600 * 24;
                break;
            default:
                break;
        }
        return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(timeType));
    }

    //判断统计条件是否勾选，勾选则显示，未勾选则隐藏
    var obj = $("#toolRetention input");
    for (var i = 0; i < obj.length; i++) {
        $('#toolRetentionTable').bootstrapTable('hideColumn', obj[i].value.toString());
        if (obj[i].type == "checkbox" && obj[i].checked) {
            $('#toolRetentionTable').bootstrapTable('showColumn', obj[i].value.toString());
        }
    }

    $(window).resize(function (e, value, row, index) {
        $('#toolRetentionTable').bootstrapTable('resetView');
    });
}

/*按条件查询方法*/
function searchdata() {
    var url = "../map/retentionStatistics";
    loadToolRetention(url);
}

/*统计项目内统计方法*/
function statInfo() {
    /*获取checkbox的选中项，判断选中项大于1则进行统计*/
    var chkobj = $("#toolRetention input[type='checkbox']:checked");
    var url = "../map/retentionStatistics";
    if (chkobj.length < 1) {
        layer.msg("至少选择一个项目统计");
        return;
    } else {
        loadToolRetention(url);
    }
}

/*导出按钮点击事件*/
function loadData() {
    /*搜索条件*/
    var data = {};
    var time = new Date();
    var timeDate = new Date(time).Format("hh:mm:ss");  //获取当前系统时间
    var time1 = ($("#startTime").val()==null||$("#startTime").val()=="")?"":$("#startTime").val()+" 00:00:00";
    if(time1==""){
        var newDate = "";
    }else{
        var timeParse = Date.parse(time1);
        var newDate = new Date(timeParse);
    }
    data.startTime = newDate;
    var time2 = ($("#endTime").val()==null||$("#endTime").val()=="")?"":$("#endTime").val()+" "+timeDate;
    if(time2==""){
        var newDates = "";
    }else{
        var timeParses = Date.parse(time2);
        var newDates = new Date(timeParses);
    }
    data.endTime = newDates;
    data.base = $("#baseTurn").val();
    data.type = $("#typeTurn").val();
    data.status = $("#statusTurn").val();
    data.toolName = $("#SearchForm input[name='toolName']").val();
    data.no = $("#SearchForm input[name='no']").val();
    /*构造统计条件*/
    var colls = new Array();  //存放统计条件中选中项的name值
    $("#toolRetention input[type='checkbox']:checked").each(function (i) {
        if ($(this).attr("name") != "num") {
            colls.push($(this).attr("name"));
        }
    });
    data.colls = colls;
    var excelColls = new Array();
    excelColls.push("id");
    $("#toolRetention input[type='checkbox']:checked").each(function (i) {
        excelColls.push($(this).attr("value"));
    });
    var collNames = new Array();
    collNames.push("序号");
    $("#toolRetention input[type='checkbox']:checked").each(function (i) {
        collNames.push($(this).parent().text());
    });
    data.excelColls = excelColls;
    data.collNames = collNames;
    $.ajax({
        type: "POST",
        url: '../map/exportExcelRetentionStatistics', /* 调用后台接口加载数据 */
        data: JSON.stringify(data),
        contentType: "application/json; charset=UTF-8",
        dataType: "json",
        success: function (result) {
            if (result.code == 0) {
                window.location.href = result.url;
            } else {
                layer.msg(result.msg);
            }
        }
    })
}

// 对Date的扩展，将 Date 转化为指定格式的String
Date.prototype.Format = function (fmt) { //author: zhengsh 2016-9-5
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
